package com.heoller.service.generator;

import com.heoller.constant.ModuleConstants;
import com.heoller.dto.CustomParam;
import com.heoller.service.strategy.GeneratorStrategy;
import com.heoller.service.template.TemplateService;
import freemarker.template.Template;
import java.util.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huliang
 * @date 2021-11-23 15:41
 */
@Service
public class ModuleGeneratorService {

    private String pomSuffix = "-pom.xml.ftl";
    private TemplateService templateService;
    private GeneratorStrategy generatorStrategy;

    @Autowired
    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    @Autowired
    public void setGeneratorStrategy(GeneratorStrategy generatorStrategy) {
        this.generatorStrategy = generatorStrategy;
    }

    public void generate(ZipOutputStream zip, String module, final CustomParam customParam) {
        Template template = templateService.getTemplate(module, module + pomSuffix);
        String modulePath = customParam.getArtifactId() + "/" + customParam.getArtifactId() + "-" + module;
        String pomFile = modulePath + "/pom.xml";
        templateService.writeFile(zip, pomFile, template, customParam);
        // 各模块后续处理
        generatorStrategy.postProcess(zip, module, customParam);
    }

    public void generateRoot(ZipOutputStream zip, final CustomParam customParam) {
        Template template = templateService.getTemplate(ModuleConstants.ROOT, ModuleConstants.ROOT + pomSuffix);
        String pomFile = customParam.getArtifactId() + "/pom.xml";
        templateService.writeFile(zip, pomFile, template, customParam);

        template = templateService.getTemplate(ModuleConstants.ROOT, "gitignore.ftl");
        String filePath = customParam.getArtifactId() + "/.gitignore";
        templateService.writeFile(zip, filePath, template, customParam);
    }
}
